package summary;

import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/4/13 16:14
 * https://leetcode-cn.com/problems/triangle/
 */
public class Title120 {

    /**
     * dp[i]表示第i+1层时最小路径和，自顶向下
     * @param triangle
     * @return
     */
    public int minimumTotal(List<List<Integer>> triangle) {
        int n = triangle.size();
        int[][] dp = new int[n][n];
        //初始化
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += triangle.get(i).get(0);
            dp[i][0] = sum;
        }
        sum = 0;
        for (int i = 0; i < n; i++) {
            sum += triangle.get(i).get(i);
            dp[i][i] = sum;
        }
        for (int i = 1; i < n; i++) {
            for (int j = 1; j < i; j++) {
                dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i - 1][j]) + triangle.get(i).get(j);
            }
        }
        //最后一行
        int min = dp[n - 1][0];
        for (int j = 0; j < n; j++) {
            if (dp[n - 1][j] < min) {
                min = dp[n - 1][j];
            }
        }
        return min;
    }



    public static void main(String[] args) {

    }
}
